//
//  main.m
//  mainuiapp
//
//  Created by com on 2021/10/14.
//

#import <UIKit/UIKit.h>
#import "AppDelegate.h"

#include <iostream>
using namespace std;

#include <dlcom/cominc.h>
#include <dlcom/objectrun.hpp>
#include "appviewimpl.h"


/*
 
 iOS < 13
 mainuiapp[873:580234] [Application] The app delegate must implement the window property if it wants to use a main storyboard file
 
 */

int RunContainer(int argc, char* argv[], const char* path) {
	
	_pid_t pid = getpid();
	
	string container_framework_path;
	container_framework_path.append(path);

	HRESULT hr = S_OK;

	const char* code = "{\"component\":[\
		  \"{F170A724-AACA-4603-BB1C-0A8EAF1C3322}:asynio:1:4\",\
		  \"{C54C9CC0-F448-4A49-A622-0467D02E8EB8}:net:2:4\",\
		  \"{201409F6-22F8-48d3-A69F-7935BDDE6BFF}:msgbus:10:4\" \
		  ]}";
	
	const char* strguid = "{409C8B8C-8467-47EE-B1BE-4E4112E64926}";
	GUID rid;
	rid = StringToGUID(strguid);
	
	CContainer com;

	SafePStringPtr containerpath;
	containerpath.ptr = container_framework_path.c_str();
	containerpath.len = container_framework_path.length();

	SafeStringPtr containercode;
	containercode.ptr = code;
	containercode.len = s_strlen(code);

	SafeStringPtr appname;
	appname.ptr = "iosapp";
	appname.len = s_strlen("iosapp");

	logi("test_main_LoadContainer");
	hr = com.LoadContainer(&containerpath);
	rc_error(hr == S_OK, S_ERROR);

	logi("test_main_CreateContainer");
	hr = com.CreateContainer(rid, &containerpath, &containercode);
	rc_error(hr == S_OK, S_ERROR);
	
	logi("test_main_InitContainer");
	hr = com.InitContainer(rid, pid, argv, argc);
	rc_error(hr == S_OK, S_ERROR);
	

	ULONG count = com.GetCompentCount(rid);
	ULONG index = com.GetStartIndex(rid, count - 1);


	CAppViewImpl *app = ALLOC_NEW CAppViewImpl();
	_lComPtr<IBase> pBase;
	hr = app->QueryInterface(IID_IBase, (void**)&pBase);
	rc_error(hr == S_OK, S_ERROR);
	
	hr = com.RegisterComponent(rid, CLSID_AppView,
		"AppView.impl.V1",
		pBase, index - 1, "appview",
		STD_COMPOENT | STD_INIT );
	rc_error(hr == S_OK, S_ERROR);
	
	logi("test_main_RunContainer");
	hr = com.RunContainer(rid, 0);
	rc_error(hr == S_OK, S_ERROR);

	logi("test_main_InitContainer");
	hr = com.UnInitContainer(rid);
	rc_error(hr == S_OK, S_ERROR);
	
	return S_SUCCESS;
}

int main(int argc, char * argv[]) {
    
    NSString * appDelegateClassName;
    
    @autoreleasepool {
        // Setup code that might create autoreleased objects goes here.
        appDelegateClassName = NSStringFromClass([AppDelegate class]);
    }
    

    NSString * frameworkPath = [[NSBundle mainBundle] privateFrameworksPath];
    const char * path = [frameworkPath UTF8String];

	RunContainer(argc, argv, path);
    
    return UIApplicationMain(argc, argv, nil, appDelegateClassName);
}
